# coding: utf-8
import json

from flask_wtf import FlaskForm
from wtforms.validators import DataRequired, Optional
from wtforms import (
    StringField, IntegerField, BooleanField,
    TextAreaField, HiddenField,
    DecimalField)


from app.forms import NonValidatingSelectField
from app.products.constant import (
    SpecUnit,
    CalculateItem, TypeToName, ParamValueType, TagType, DraftStatus)
from app.products.models import TechnologyParams


class JsonFiled(StringField):

    def process_data(self, value):
        if isinstance(value, (list, dict, tuple)):
            value = json.dumps(value, ensure_ascii=False)
        super(JsonFiled, self).process_data(value)


class ProductParamEditForm(FlaskForm):
    product_type_id = NonValidatingSelectField(
        '产品类型',
        coerce=int,
        choices=list(),
        validators=[DataRequired()]
    )
    name = StringField('技术参数名称', validators=[DataRequired()])
    default_value = StringField('默认值')
    unit = NonValidatingSelectField(
        '单位',
        coerce=int,
        choices=SpecUnit.mapping.items(),
        default=SpecUnit.NIL
    )

    calculate_item = NonValidatingSelectField(
        '计算项',
        coerce=int,
        choices=CalculateItem.mapping.items()
    )
    value_type = NonValidatingSelectField(
        '参数类型',
        coerce=int,
        choices=ParamValueType.mapping.items()
    )
    display_rule = StringField('显示规则', default='{}')
    is_required = BooleanField('是否必填', default=False)
    is_display = BooleanField('是否标题元素', default=False)
    parent_id = NonValidatingSelectField('父id', coerce=int, choices=[])
    options = JsonFiled('选项值 如:[\"白色\", \"黑色\"]', default='[]')
    tag_type = NonValidatingSelectField(
        '标签类型',
        coerce=int,
        choices=list(TagType.mapping.items()),
        validators=[DataRequired()]
    )
    placeholder = StringField('输入提示')
    weight = IntegerField('权重', validators=[Optional()], default=0)

    def parent_choices(self):
        if not self.product_type_id.data:
            self.product_type_id.data = TypeToName.MODULE_GROUP
        self.parent_id.choices = (
            [(0, '无')] +
            TechnologyParams.params_parents_choices(self.product_type_id.data)
        )

    def __init__(self, *args, **kwargs):
        super(ProductParamEditForm, self).__init__(*args, **kwargs)
        self.options.data = self.options.data or '[]'
        self.display_rule.data = self.display_rule.data or '{}'
        self.weight.data = self.weight.data or 0


class ProductParamForm(ProductParamEditForm):
    """
    产品技术参数表单
    """

    def __init__(self, *args, **kwargs):
        super(ProductParamForm, self).__init__(*args, **kwargs)
        self.product_type_id.choices = list(TypeToName.mapping.items())
        if not self.product_type_id.data:
            self.product_type_id.data = TypeToName.MODULE_GROUP
        self.parent_id.choices = (
            [(0, '无')] +
            TechnologyParams.params_parents_choices(self.product_type_id.data)
        )


class ProductBaseForm(FlaskForm):
    product_type_id = NonValidatingSelectField(
        '产品类型',
        coerce=int,
        choices=list(),
        validators=[DataRequired()]
    )
    brand_id = NonValidatingSelectField(
        '品牌',
        validators=[DataRequired()],
        choices=[],
        coerce=int
    )
    price = DecimalField('成本价', default=0)
    suggest_price = DecimalField('建议零售价', default=0)
    source = StringField('信息来源', validators=[Optional()], default='')
    weight = IntegerField('权重', validators=[Optional()], default=0)
    params = HiddenField()
    remark = TextAreaField('产品说明')
    pictures = HiddenField(default='[]')
    specs = HiddenField(default='[]')
    brand_model_id = NonValidatingSelectField(
        '型号',
        coerce=int,
        choices=[(0, '--请选择型号--')]
    )

    def __init__(self, *args, **kwargs):
        super(ProductBaseForm, self).__init__(*args, **kwargs)


class ProductForm(ProductBaseForm):
    """
    产品表单
    """

    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.product_type_id.choices = (
            [(0, '--请选择产品类型--')] + list(TypeToName.mapping.items())
        )


class ProductSearchForm(FlaskForm):
    """
    产品查询条件表单
    """
    product_type_id = NonValidatingSelectField(
        '产品类型',
        coerce=int,
        choices=list(),
        validators=[Optional()]
    )
    name = StringField('产品名称', validators=[Optional()])
    brand = StringField('品牌', validators=[Optional()])

    def __init__(self, *args, **kwargs):
        super(ProductSearchForm, self).__init__(*args, **kwargs)
        self.product_type_id.choices = (
            [(0, '--请选择产品类型--')] + list(TypeToName.mapping.items())
        )


class ProductBatchForm(FlaskForm):
    """
    产品批量更新查询条件表单
    """
    product_type_id = NonValidatingSelectField(
        '产品类型',
        coerce=int,
        choices=list(),
        validators=[DataRequired()]
    )
    spec_id = NonValidatingSelectField(
        '产品规格', validators=[DataRequired()],
        choices=list()
    )

    def __init__(self, *args, **kwargs):
        super(ProductBatchForm, self).__init__(*args, **kwargs)
        self.product_type_id.choices = (
            [(0, '--请选择产品类型--')] + list(TypeToName.mapping.items())
        )


class DraftApprovalForm(FlaskForm):
    """
    产品草稿审核表单
    """
    remark = TextAreaField('审核备注', validators=[DataRequired()])
    status = HiddenField()


class ParamSearchForm(FlaskForm):
    """
    产品查询条件表单
    """
    product_type_id = NonValidatingSelectField(
        '产品类型',
        coerce=int,
        choices=list(),
        validators=[Optional()]
    )
    name = StringField('技术参数名称', validators=[Optional()])

    def __init__(self, *args, **kwargs):
        super(ParamSearchForm, self).__init__(*args, **kwargs)
        self.product_type_id.choices = (
            [(0, '--请选择产品类型--')] + list(TypeToName.mapping.items())
        )


class DraftSearchForm(FlaskForm):
    """
    """
    status = NonValidatingSelectField(
        '审核状态',
        coerce=int,
        choices=[(0, '--请选择审核状态--')] + list(
            DraftStatus.to_options()
        ),
        validators=[Optional()]
    )

